import React, { useState, useRef, useEffect } from 'react';
import { Button, message, Spin, Tabs, Popconfirm } from 'antd';
import ProTable from '@ant-design/pro-table';
import { Form } from '@ant-design/compatible';
import { useRequest, useInViewport } from '@umijs/hooks';
import TreeControlled from '@/components/blocks/TreeControlled';
import styles from './index.less';
import { getDepartmentChildInfo, updateDepartStatus, getDepartmentTreeByRole } from './service';
import AuthComponent from '@/components/Authorized/AuthComponent';

const TableList = () => {
  const searchRef = useRef();
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [height, controlH] = useState(300);
  const [isCollapse, controlC] = useState(true);
  // 用于重置缓存页面的tab选中状态
  const inViewPort = useInViewport(() => document.querySelector('#pageViewId'));
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 364.5);
    } else {
      controlH(document.body.clientHeight - 588.5);
    }
  }, [isCollapse])

  const reloadTable = function reloadTable() {
    if (searchRef.current) {
      searchRef.current.click();
    }
  };

  const options = {
    changeState: {
      func: ({ toBgnF, id }) => updateDepartStatus({ status: toBgnF ? '0' : '1', id }),
      callback: (_, row) => {
        message.success(row.toBgnF ? '启用成功!' : '禁用成功!');
        reloadTable();
      },
    },
  };

  const optionHandle = function optionHandle(key, row) {
    options[key].func(row).then(res => options[key].callback(res, row));
  };

  const columns = [
    {
      title: '部门代码',
      dataIndex: 'toId',
      valueType: 'text',
    },
    {
      title: '部门名称',
      dataIndex: 'toFname',
      valueType: 'text',
    },
    {
      title: '操作',
      valueType: 'option',
      dataIndex: 'id',
      width: 100,
      hideInTable: !AuthComponent.getAuth('user.dept.enable_disable'),
      render: (text, row) => [
        <Popconfirm
          title={`你确定要${row.toBgnF ? '启用' : '禁用'}该部门吗？`}
          onConfirm={() => optionHandle('changeState', row)}
          okText="确定"
          cancelText="取消"
        >
          <Button type="link" style={{ padding: 0 }}>
            {row.toBgnF ? '启用' : '禁用'}
          </Button>
        </Popconfirm>,
      ],
    },
    {
      title: '状态',
      dataIndex: 'toBgnF',
      initialValue: '',
      valueEnum: {
        '0': { text: '启用', status: 'Success' },
        '1': { text: '禁用', status: 'Default' },
      },
      hideInSearch: true,
    },
    {
      title: '员工数量',
      dataIndex: 'personCount',
      hideInSearch: true,
    },
    {
      title: '最后更新时间',
      dataIndex: 'updateTime',
      hideInSearch: true,
    },
  ];

  const [dept, setDept] = useState({});
  const [inited, setInited] = useState(false);
  useEffect(() => {
    if (!inited) {
      setInited(true);
    } else {
      reloadTable();
    }
  }, [dept.id, inited]);

  const [treeTitle, setTreeTitle] = useState('');

  const { loading, data } = useRequest(getDepartmentTreeByRole, {
    onSuccess: ([root]) => {
      setTreeTitle(root.title);
      setSelectedKeys([root.key]);
      setDept(root);
    },
  });

  const onSelect = function onSelect(keys, { selected, node }) {
    setDept(node.props.dataRef ? node.props.dataRef : node.props);
    if (selected) {
      setSelectedKeys(keys);
    }
  };

  return (
    <section id="pageViewId" className={styles.wrapper}>
      <Tabs className={styles.treeWrapper}>
        <Tabs.TabPane tab={treeTitle} key="1">
          <Spin spinning={loading}>
            <TreeControlled
              className={styles.tree}
              selectable
              data={data}
              selectedKeys={selectedKeys}
              setSelectedKeys={onSelect}
            />
          </Spin>
        </Tabs.TabPane>
      </Tabs>

      <div className={`${styles.table} rest-pro-table-form-compact`}>
        <ProTable
          className={`rest-pro-table-form-compact ${isCollapse ? 'closeDeptTable' : 'deptTable'}`}
          scroll={{ x: 1200, y: height }}
          pagination={{
            showSizeChanger: true,
            showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
          }}
          options={{density:false,fullScreen:true, reload:false, setting:true}}
          search={{
            searchText: (
              <span ref={searchRef} href>
                查询
              </span>
            ),
            onCollapse: val => {
              controlC(val);
            }
          }}
          size={'small'}
          headerTitle={
            <span style={{ paddingRight: 10, fontWeight: 'bold', color: '#000' }}>
              {dept.title}
            </span>
          }
          rowKey="id"
          request={params =>
            dept.id ? getDepartmentChildInfo({ ...params, deptId: dept.id }) : Promise.resolve([])
          }
          columns={columns}
        />
      </div>
    </section>
  );
};

export default Form.create()(TableList);
